package com.distribute.framework.core.web.helper;

import com.distribute.framework.core.web.helper.Utils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class SpringBeanHelper implements BeanFactoryAware,ApplicationContextAware{
	
	private static BeanFactory beanFactory; //BEAN工厂	
	
	@SuppressWarnings("static-access")
	public void setBeanFactory(BeanFactory arg0) throws BeansException {
		this.beanFactory = arg0;
	}
	public void setApplicationContext(ApplicationContext arg0)throws BeansException {
		this.springContext = arg0;
	}
	/**
	 * 获取一个被spring托管的bean
	 * @param name
	 * @return
	 */
	public static <T> T GetBean(String name){
		if(beanFactory==null){
			String strTips = "您当前未加载spring,可以尝试在应用启动时手工加载spring,代码如：L.initSpring(ApplicationContext);";
			throw new RuntimeException(strTips);
		}
		return (T) (beanFactory.containsBean(name) ? beanFactory.getBean(name) : null);
	}
	
	public static void initSpring(ApplicationContext applicationContext){
		if(springContext==null){
			springContext = applicationContext;
			beanFactory = springContext;
			ConfigHelper.setEnvironment(applicationContext.getEnvironment());
		}
	}
	
	/**
     * @desc 向spring容器注册bean
     * @param beanName
     * @param beanDefinition
     */
	public static void registerBean(String beanName, BeanDefinition beanDefinition) {
        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) springContext;
        BeanDefinitionRegistry beanDefinitonRegistry = (BeanDefinitionRegistry) configurableApplicationContext.getBeanFactory();
        beanDefinitonRegistry.registerBeanDefinition(beanName, beanDefinition);
    }
	
	public static ApplicationContext springContext = null;

	
}